<?php
/**
 * Auther: Joshua Conero
 * Date: 2017/11/24 0024 22:14
 * Email: brximl@163.com
 * Name: 系统处理API
 */

namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Role;
use think\Db;
use think\facade\Cache;

class Aurora extends Api
{
    /**
     * (系统分组)系统菜单数据
     * @return bool|\think\response\Json
     */
    public function menu(){
        $check = $this->needLoginNet($uid);
        if($check) return $check;
        $dd = [];
        $role = new Role();
        $roles = $role->getRoles();
        // 开发者、系统管理员角色检测
        if($roles && is_array($roles) && (in_array('developer', $roles) || in_array('admin', $roles))){
            $dd[] = ['text'=>'后台管理', 'url'=>urlBuild('!admin:')];
        }
        //$dd = $roles;
        return $this->FeekMsg($dd);
    }

    /**
     * {controller: table.column.filed, name: value, limit: 10}
     * @return bool|\think\response\Json
     */
    public function autocomplete(){
        $check = $this->needLoginNet($uid);
        if($check) return $check;

        $ctl = input('controller');
        $name = input('name');

        if(!$ctl || !$name || substr_count($ctl, '.') > 1){
            return $this->FeekMsg('请求参数不足和无效！(controller, name)');
        }

        $limit = input('limit', 10);
        $tmpArr = explode('.', $ctl);
        if(count($tmpArr) == 2){
            list($table, $col) = $tmpArr;
            $filed = $col;
        }else{
            list($table, $col, $filed) = $tmpArr;
        }

        $data = ['values' => []];
        try{
            // 数据缓存
            $shaId = sha1($table.$filed.$col.$name);
            $vs = Cache::get($shaId);

            if(empty($vs)){
                $rs = Db::table($table)
                    ->field($filed)
                    ->where($col, 'like', "%$name%")
                    ->where("`$col` is not null")
                    ->limit($limit)
                    ->group($filed)
                    ->select()
                ;


                $vs = [];
                foreach ($rs as $v){
                    $vs[] = $v[$filed];
                }
                Cache::set($shaId, $vs);
            }
            $data['values'] = $vs;
        }catch (\Exception $e){
            \think\facade\Log::error($e->getMessage());
        }
        return $this->FeekMsg($data);
    }

    /**
     * 缓存清理
     */
    public function cache_clear(){
        Cache::clear();
        $this->success('缓存已清除！');
    }
}